﻿using System;
using ESoft.Extensions;
using ESoft.Redis;
using Microsoft.AspNetCore.Http;

namespace ESoft.AspNetCore.Login
{
    /// <summary>
    /// 会话服务
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class SessionService<T> : ISessionService<T> where T:IApplicationSession
    {
        private readonly IRedisService _redisService;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly double liveTime=7*24;

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="redisService"></param>
        /// <param name="httpContextAccessor"></param>
        public SessionService(IRedisService redisService, IHttpContextAccessor httpContextAccessor)
        {
            _redisService = redisService;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 当前用户信息
        /// </summary>
        /// <param name="sid"></param>
        /// <returns></returns>
        public T GetLoginUser(string sid)
        {
            return _redisService.Get<T>("P:" + sid);
        }

        /// <summary>
        /// 当前用户信息
        /// </summary>
        /// <returns></returns>
        public T GetLoginUser()
        {
            string authorize = _httpContextAccessor.HttpContext.Request.Headers["authorization"];
            if (authorize.IsNullOrWhiteSpace() || !authorize.StartsWith("Bearer "))
            {
                return default;
            }

            var token = authorize.Split(" ")[1];
            return _redisService.Get<T>("P:" + token);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string InsertOrUpdateSession(T user)
        {
            if (user == null || user.UserId.IsNullOrWhiteSpace()) return null;
            string id = Guid.NewGuid().ToStringN();
            user.LastAccessTime = DateTime.Now;
            _redisService.Set<IApplicationSession>("P:" + id, user, TimeSpan.FromHours(liveTime));
            return id;
        }

        /// <summary>
        /// 刷新会话
        /// </summary>
        /// <param name="sid"></param>
        /// <returns></returns>
        public T Refresh(string sid)
        {
            var loginUser = GetLoginUser(sid);
            if (loginUser == null || loginUser.UserId.IsNullOrWhiteSpace()) return default;
            if (DateTime.Now.Subtract(loginUser.LastAccessTime).TotalHours < 1)
            {
                return loginUser;
            }
            _redisService.Set("P:" + sid, loginUser, TimeSpan.FromHours(liveTime));
            return loginUser;
        }
    }
}
